// 公共方法
import { isNull, showSuccess, clone, msg, clog, showError } from '/@/utils';
import { enumCode } from '/@/const';
import { decodeXueDaiTiaoMa } from '/@/utils/decodeXueDaiTiaoMa';
import { useConfirmDialog } from '/@/hooks';
import { InvRuKuApi, InvRuKuMingXiInput, InvRuKuOutput } from '/@/api/inv/InvRuKu';
import { getBasXueYeLaiYuanMoRen, getXueYePinZhongInfo, getBasXueYeChanPin } from '/@/stores/baseInfo';
import { loginInfo } from '/@/stores/baseInfo';

//  #region DOM元素
export const billPanelRef = ref();
export const formRef = ref();
export const formMingXiRef = ref();
export const listRef = ref();
export const scanRef = ref();
export const editPageRef = ref();
//  #endregion

//  #region data数据
const initCtx = () => ({
	isEdit: false,
	loading: false,
	entity: { danJuLeiXing: '手工入库', ruKuYuanQuId: loginInfo.value.yuanQuId } as InvRuKuOutput,
	mingXiTable: [] as InvRuKuMingXiInput[],
	mingXi: { xianXueMa: '', chanPinId: '', mingCheng: '', abo: '', rhD: '', danWei: '', xueDaiWaiGuan: '正常' } as InvRuKuMingXiInput,
});

export const ctx = reactive(initCtx()); //  使用 reactive 初始化
//  #endregion

// 清空表单数据
export const newEntity = async () => {
	// 实体值ctx初始化
	Object.assign(ctx, initCtx());
	ctx.entity.xueYeLaiYuanId = (await getBasXueYeLaiYuanMoRen())?.id
	ctx.entity.ruKuYuanQuId = loginInfo.value.yuanQuId;
	ctx.isEdit = true;
	// 扫码框获得焦点
	scanRef.value?.focus();
};

// 列表--查看按钮代码
export const loadEntity = (entity: InvRuKuOutput) => {
	if (isNull(entity) || isNull(entity.id)) {
		return;
	}
	// 调用接口获取数据
	InvRuKuApi.get(entity.id).then((res) => {
		formRef.value.resetFields();
		// 赋值实体
		ctx.entity = res.master;
		// 赋值明细
		ctx.mingXiTable = res.mingXiList;
		ctx.isEdit = false;
	});
};

// 提交
export const submit = async () => {
	//  表单验证
	const validate = await formRef?.value?.validate();
	if (!validate) return;

	await useConfirmDialog('确认提交吗?');

	if (ctx.mingXiTable.length == 0) {
		msg.error('请添加血液信息!');
		return;
	}

	if (isNull(ctx.entity.id)) {
		//  这样子写，如果报错了，界面上也显示了 已生效
		//  ctx.entity.danJuZhuangTai = enumCode.Djzt.已生效;
		const params = {
			...ctx.entity,
			danJuZhuangTai: enumCode.Djzt.已生效,
			mingXiList: ctx.mingXiTable,
		}
		ctx.entity = await InvRuKuApi.add(params);
	} else {
		//  入库后明细不能再修改, 只能修改主表
		//  await InvRuKuApi.update({ ...ctx.entity, mingXiList: ctx.mingXiTable });
	}
	showSuccess();
	ctx.isEdit = false;

	close();
};

// 修改产品码,切换品种,单位
export const changeChanPin = async () => {
	var chanpin = await getBasXueYeChanPin(ctx.mingXi.chanPinId);
	if (chanpin) {
		ctx.mingXi.pinZhongId = chanpin.pinZhongId ?? '';
		ctx.mingXi.daLei = chanpin.daLei ?? '';
		ctx.mingXi.mingCheng = chanpin.mingCheng ?? '';
		var pinZhong = getXueYePinZhongInfo(ctx.mingXi.pinZhongId);
		ctx.mingXi.danWei = pinZhong?.danWei ?? '';
	} else {
		showError('未知的血液产品码! 请新增血液产品');
	}
}

// 添加按钮
export const addMingXi = async () => {
	//  表单验证
	const validate = await formMingXiRef?.value?.validate();

	if (!validate) return;

	ctx.mingXi.id = ctx.mingXiTable ? ctx.mingXiTable.length + 1 : 1;
	ctx.mingXi.xianXueMa = ctx.mingXi.xianXueMa.replace(/\s+/g, '');
	ctx.mingXi.chanPinId = ctx.mingXi.chanPinId.replace(/\s+/g, '');

	// 根据献血码、产品码 查询血液是否存在明细中
	const inListItem = ctx.mingXiTable.find((item: InvRuKuMingXiInput) => item.xianXueMa == ctx.mingXi.xianXueMa && item.chanPinId == ctx.mingXi.chanPinId);
	if (inListItem) {
		msg.error('该血液已存在列表中!');
		return;
	}

	ctx.mingXiTable.push(clone(ctx.mingXi));

	ctx.mingXi = { xueDaiWaiGuan: "正常" } as InvRuKuMingXiInput;
	scanRef.value?.focus();
};

// 查看
export const showMingXi = (row: any) => {
	editPageRef.value.open(row);
};

// 修改血液信息
export const editMingXi = (row: InvRuKuMingXiInput) => {
	row.xianXueMa = row.xianXueMa.replace(/\s+/g, '');
	row.chanPinId = row.chanPinId.replace(/\s+/g, '');
	// 根据献血码、产品码 查询血液是否存在明细中
	const inListItem = ctx.mingXiTable.find((item: InvRuKuMingXiInput) => item.id != row.id && item.xianXueMa == row.xianXueMa && item.chanPinId == row.chanPinId);
	if (inListItem) {
		msg.error('该血液已存在列表中!');
		return;
	}

	//  找到要修改的项的索引
	const index = ctx.mingXiTable.findIndex((item: InvRuKuMingXiInput) => item.id === row.id);
	if (index !== -1) {
		//  直接修改数组中的对象
		ctx.mingXiTable[index] = { ...ctx.mingXiTable[index], ...row };
		showSuccess('已修改');
	} else {
		console.warn('未找到匹配的项');
	}
};

export const deleteBlood = (row: any) => {
	console.log('删除方法执行', row.id);

	//  找到要删除的项的索引
	ctx.mingXiTable = ctx.mingXiTable.filter((item: InvRuKuMingXiInput) => item.id !== row.id); //  删除所有等于3的元素
	showSuccess('已删除');
};

/** 获取扫码信息 */
export const getBarcode = (code: string | undefined) => {
	if (!code) return;
	const scanResult = decodeXueDaiTiaoMa(code);
	if (scanResult.type == 'error') {
		msg.error(scanResult.message ?? '请扫描正确的条码!');
		scanRef.value.select();
		return;
	}
	if (scanResult.type == 'XueXing') {
		ctx.mingXi.abo = scanResult.abo;
		ctx.mingXi.rhD = scanResult.rhD;
		return;
	}
	ctx.mingXi[scanResult.type] = scanResult.message;
	changeChanPin();
};

export const print = () => {
	billPanelRef.value.printWeb('billno', 'detail');
	showSuccess('打印');
};

export const printALL = () => {
	billPanelRef.value.printWeb('billno', 'all');
	showSuccess('printALL');
};
